<?php
/**
 * 支付宝
 * @author chenlisong E-mail:chenlisong1021@163.com 
 * @version 创建时间：2016年12月20日 上午10:27:34 
 * 类说明
 */
class AlipayAction extends BaseAction{
	
	public function _initialize(){
		header("Content-Type: text/html;charset=utf-8");
		$this->param = $_REQUEST;
		vendor('Alipay.Corefunction');
		vendor('Alipay.Md5function');
		vendor('Alipay.Notify');
		vendor('Alipay.Submit');
	}
	
	/**
	 *订单支付宝支付
	 */
	public function alipayPayOrder(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');
		$param = $this->param;
		if(empty($param['orderCode'])){
			$this->error("参数错误！");
		}
		//判断订单状态是否正确
		$where['code'] = $param['orderCode'];
		$where['flag'] = 1;
		$where['status'] = 1;
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			$this->error("错误的订单状态，请重新下单！");
		}
		//封装body
		$map['order_code'] = $param['orderCode'];
		$map['flag'] = 1;
		$goodslist = $OrderDetails->where($map)->field('name,num')->select();
		foreach ($goodslist as $key=>$val){
			$body .= $val['name'].$val['num']."份.";
		}
		$name = '佳好友网络订单，单号：'.$param['orderCode'];
		$price = ($info['real_price'] + $info['mail_fee']);//加上运费
		$parameter = array(
				"service" => "create_direct_pay_by_user",
				"partner" => C('alipay_config.partner'),
				"payment_type" => "1",//支付类型 必填，不能修改
				"notify_url" => C('alipay_web_order_config.notify_url'),//服务器异步通知页面路径
				"return_url" => C('alipay_web_order_config.return_url'),//页面跳转同步通知页面路径
				"seller_email" => C('alipay_web_order_config.seller_email'),//卖家支付宝帐户必填
				"out_trade_no" => $info['code'],
				"subject" => $name,//订单名称
				"total_fee" => $price,
				"body" => $body,
				"anti_phishing_key" => time(),//防钓鱼时间戳 
				"exter_invoke_ip" => get_client_ip(),//客户端的IP地址
				"_input_charset" => C('alipay_config.input_charset')
		);
		//建立请求
		$alipaySubmit = new AlipaySubmit(C('alipay_config'));
		$html_text = $alipaySubmit->buildRequestForm($parameter,"post", "正在跳转到支付宝...");
		echo $html_text;
	}
	
	/**
	 * 异步处理
	 */
	public function orderNotifyurl(){
		$alipay_config=C('alipay_config');
		//计算得出通知验证结果
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {
			//验证成功
			$code = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$total_fee = $_POST['total_fee'];//交易金额
			$buyer_email = $_POST['buyer_email'];//买家帐号
			if($_POST['trade_status'] == 'TRADE_FINISHED') {
				$this->handleOrder($code,$trade_no,$total_fee,$buyer_email);
			}else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				$this->handleOrder($code,$trade_no,$total_fee,$buyer_email);
			}
			echo "success";
		}else {
			echo "fail";
		}
	}
	
	/**
	 * 同步处理
	 */
	public function orderReturnurl(){
		$alipay_config = C('alipay_config');
		$alipayNotify = new AlipayNotify($alipay_config);//计算得出通知验证结果
		$verify_result = $alipayNotify->verifyReturn();
		if($verify_result) {
			//验证成功
			$code = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$total_fee = $_POST['total_fee'];//交易金额
			$buyer_email = $_POST['buyer_email'];//交易金额
			if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				$this->handleOrder($code,$trade_no,$total_fee,$buyer_email);
				$this->redirect('Order/index');
			}else {
				$this->redirect('Order/index');
			}
		}else {
			echo "支付失败！";
		}
	}
	
	/**
	 * 处理订单
	 */
	private function handleOrder($code,$trade_no,$total_fee,$buyer_email){
		//付款成功进行订单处理
		$Order = M('Order');
		$where['code'] = $code;
		$info = $Order->where($where)->find();
		if(in_array($info['status'], array(1,-1))){
			//订单状态更改
			$data['status'] = 2;
			$data['flag'] = 1;
			$data['pay_type'] = 1;
			$data['pay_time'] = time();
			$data['pay_code'] = $trade_no;
			$data['pay_email'] = $buyer_email;
			$data['update_time'] = time();
			$Order->where($where)->save($data);
		}else{
			$msg = "交易号为：".$trade_no."，订单编号为".$code."使用支付宝支付完成，但是订单状态为非正常状态！";
			writeLog($msg);
		}
		return true;
	}
	
	/**
	 * 充值
	 */
	public function rechargeAlipay(){
		$RechargeSetting = M('RechargeSetting');$RechargeLog = M('RechargeLog');
		$param = $this->param;
		$where['flag'] = 1;
		$where['id'] = $param['rechargeId'];
		$info = $RechargeSetting->where($where)->find();
		if(empty($info)){
			$this->error("错误的充值金额！");
		}
		$code = date('YmdHis').rand(10,99);
		$data['code'] = $code;
		$data['user_id'] = $_SESSION['HS_USER_ID'];
		$data['recharge_price'] = $info['recharge_price'];
		$data['give_price'] = $info['give_price'];
		$data['create_time'] = time();
		$RechargeLog->add($data);
		$body = "在线充值".$info['recharge_price']."返利".$info['give_price'];
		$name = '佳好友在线充值';
		$parameter = array(
				"service" => "create_direct_pay_by_user",
				"partner" => C('alipay_config.partner'),
				"payment_type" => "1",//支付类型 必填，不能修改
				"notify_url" => C('alipay_web_recharge_config.notify_url'),//服务器异步通知页面路径
				"return_url" => C('alipay_web_recharge_config.return_url'),//页面跳转同步通知页面路径
				"seller_email" => C('alipay_web_recharge_config.seller_email'),//卖家支付宝帐户必填
				"out_trade_no" => $code,
				"subject" => $name,//订单名称
				"total_fee" => $info['recharge_price'],
				"body" => $body,
				"anti_phishing_key" => time(),//防钓鱼时间戳
				"exter_invoke_ip" => get_client_ip(),//客户端的IP地址
				"_input_charset" => C('alipay_config.input_charset')
		);
		//建立请求
		$alipaySubmit = new AlipaySubmit(C('alipay_config'));
		$html_text = $alipaySubmit->buildRequestForm($parameter,"post", "正在跳转到支付宝...");
		echo $html_text;
	}
	
	/**
	 * 异步处理
	 */
	function rechargeNotifyurl(){
	$alipay_config=C('alipay_config');
		//计算得出通知验证结果
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {
			//验证成功
			$code = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$total_fee = $_POST['total_fee'];//交易金额
			$buyer_email = $_POST['buyer_email'];//交易金额
			if($_POST['trade_status'] == 'TRADE_FINISHED') {
				$this->handleRecharge($code, $trade_no, $buyer_email);
			}else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				$this->handleRecharge($code, $trade_no, $buyer_email);
			}
			echo "success";        //请不要修改或删除
		}else {
			//验证失败
			echo "fail";
		}
	}
	
	/**
	 * 同步处理
	 */
	function rechargeReturnurl(){
		$alipay_config= C('alipay_config');
		$alipayNotify = new AlipayNotify($alipay_config);//计算得出通知验证结果
		$verify_result = $alipayNotify->verifyReturn();
		if($verify_result) {
			//验证成功
			$code = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$total_fee = $_POST['total_fee'];//交易金额
			$buyer_email = $_POST['buyer_email'];//交易金额
			if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				$this->handleRecharge($code, $trade_no, $buyer_email);
				$this->redirect('User/accounts');//跳转到配置项中配置的支付成功页面；
			}else {
				$this->redirect('User/accounts');//跳转到配置项中配置的支付失败页面；
			}
		}else {
			//验证失败
			echo "支付失败！";
		}
	}
	
	private function handleRecharge($code,$trade_no,$buyer_email){
		//付款成功进行订单处理
		$RechargeLog = M('RechargeLog');$User = M('User');$UserDetails = M('UserDetails');$Fields = M('Fields');
		$where['code'] = $code;
		$info = $RechargeLog->where($where)->find();
		$balance = (float) $User->where('id = '.$info['user_id'])->getField('balance');
		if(in_array($info['status'], array(1,-1))){
			//给用户加金额（含赠送）
			$data[0]['user_id'] = $info['user_id'];
			$data[0]['title'] = "支付宝充值";
			$data[0]['type'] = 1;
			$data[0]['price'] = $info['recharge_price'];
			$data[0]['last_price'] = $balance;
			$data[0]['create_time'] = time();
			$data[1]['user_id'] = $info['user_id'];
			$data[1]['title'] = "充值赠送";
			$data[1]['type'] = 1;
			$data[1]['price'] = $info['give_price'];
			$data[1]['last_price'] = $balance + $info['recharge_price'];
			$data[1]['create_time'] = time();
			$UserDetails->addAll($data);
			$User->where('id = '.$info['user_id'])->setInc('balance',($info['recharge_price'] + $info['give_price']));
			//给推荐人分润
			$parentId = $User->where('id = '.$info['user_id'])->getField('parent_id');
			if(!empty($parentId)){
				$bl = (float) $Fields->where('flag = 1 and field ="app_recharge_return_rate"')->getField('value');
				$price = sprintf("%.2f",$info['recharge_price'] * $bl);
				$udata['user_id'] = $parentId;
				$udata['title'] = "充值返利";
				$udata['type'] = 1;
				$udata['price'] = $price;
				$udata['from_user_id'] = $info['user_id'];
				$udata['last_price'] = (float) $User->where('id = '.$parentId)->getField('balance');
				$udata['create_time'] = time();
				$UserDetails->add($udata);
				$User->where('id = '.$parentId)->setInc('balance',$price);
			}
			//订单状态更改
			$dataOrder['status'] = 2;
			$dataOrder['flag'] = 1;
			$dataOrder['pay_type'] = 1;
			$dataOrder['pay_time'] = time();
			$dataOrder['pay_code'] = $trade_no;
			$dataOrder['pay_email'] = $buyer_email;
			$dataOrder['update_time'] = time();
			$RechargeLog->where($where)->save($dataOrder);
		}else{
			$msg = "【充值】交易号为：".$trade_no."，订单编号为".$code."使用支付宝支付完成，但是订单状态为非正常状态！";
			writeLog($msg);
		}
		return true;
	}
}